package com.example.his.api.mis.service.impl;

import cn.hutool.core.map.MapUtil;
import com.example.his.api.common.PageUtils;
import com.example.his.api.db.dao.OrderDao;
import com.example.his.api.front.service.PaymentService;
import com.example.his.api.mis.service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service("MisOrderServiceImpl")
public class OrderServiceImpl implements OrderService {
  
  
  @Resource
  private OrderDao orderDao;
  
  @Resource
  private PaymentService paymentService;
  
  @Override
  public PageUtils searchByPage(Map param) {
    ArrayList <HashMap> list = new ArrayList <>();
    long count = orderDao.searchCount(param);
    if(count > 0) {
      list = orderDao.searchByPageOfMis(param);
    }
    int page = MapUtil.getInt(param, "page");
    int length = MapUtil.getInt(param, "length");
    return new PageUtils(list, count, page, length);
  }
  
  //  同步付款结果
  @Override
  @Transactional
  public int checkPaymentResult(String[] outTradeNoArray) {
    int i = 0;
    for(String outTradeNo: outTradeNoArray) {
      String transactionId = paymentService.searchPaymentResult(outTradeNo);
      if(transactionId != null) {
        int rows = orderDao.updatePayStatus(new HashMap() {{
          put("outTradeNo", outTradeNo);
          put("transactionId", transactionId);
        }});
        i += rows;
      }
    }
    return i;
  }
  
  @Override
  public boolean deleteById(int id) {
    long count = orderDao.deleteById(id);
    return count == 1;
  }
  
  @Override
  @Transactional
  public boolean updateRefundStatusById(int id) {
    int rows = orderDao.updateRefundStatusById(id);
    return rows == 1;
  }
  
  
}
